package triFileSystem;

import triStorage.*;
import transaction.*;
import utils.Constants;
import utils.Converter;

public class PageWriter implements IWriter {

	private int pageId;
	private int pos;
	private TriMMPFile mmpfile;
	
	public PageWriter(int pageId, TriMMPFile mmpfile) {
		this.pos = 0;
		this.pageId = pageId;
		this.mmpfile = mmpfile;
	}
	
	@Override
	public void appendInt(int value, Transaction tx) {
		//mmpfile.writeInt(pageId, pos, value);
		mmpfile.appendInt(pageId, pos, value, tx);
		pos += Constants.INT_SIZE;
		
	}

	@Override
	public void appendLong(long value, Transaction tx) {
		//mmpfile.writeLong(pageId, pos, value);
		mmpfile.appendLong(pageId, pos, value, tx);
		pos += Constants.INT_SIZE;
	}

	@Override
	public void appendString(String value, Transaction tx) {
		if (value == null) { 
			appendInt(-1, tx);
			return;
		}
		
		int len = value.length();
		appendInt(len, tx);
		if (len == 0)
			return;
		
		appendInt(len, tx);
		byte[] str = new byte[len];
		Converter.String2Bytes(value, str, 0);
		//mmpfile.writeBytes(pageId, pos, str, 0, len);
		mmpfile.appendBytes(pageId, pos, str, 0, len, tx);
		
		pos += len;
	}

	@Override
	public long getWritePos() {
		return mmpfile.PAGE_SIZE * pageId + pos;
	}

	@Override
	public void dispose() {
		// TODO Auto-generated method stub
		
	}

}
